package com.zero.yygh.common.utils;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

/**
 * @author zero
 * @desc HttpClient工具类
 * @create 2021/4/7
 */
public class HttpClientUtils {

    /**
     * 连接超时时长， 10000ms
     */
    public static final int CONNECT_TIMEOUT = 10000;
    /**
     * 读取超时时长，10000ms
     */
    public static final int READ_TIMEOUT = 10000;

    public static final String MIME_TYPE_XML = "application/xml";
    public static final String MIME_TYPE_FORM = "application/x-www-form-urlencoded";
    public static final String PROTOCOL_HTTPS = "https";

    private static HttpClient client;

    static {
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();;
        cm.setMaxTotal(128);
        cm.setDefaultMaxPerRoute(128);
        client = HttpClients.custom().setConnectionManager(cm).build();
    }

    /**
     * 根据url 以及请求参数发送post请求
     * form表单形式、默认 utf-8、连接超时时长 10s
     * @author zero
     * @date 2021/4/8 11:34
     * @param url 请求路径
     * @param paramStr 请求参数
     * @return java.lang.String
     */
    public static String postParameters(String url, String paramStr) throws IOException, GeneralSecurityException {
        return post(url, paramStr, MIME_TYPE_FORM, Consts.UTF_8.toString(), CONNECT_TIMEOUT, READ_TIMEOUT);
    }

    /**
     * post提交
     * @author zero
     * @date 2021/4/8 11:40
     * @param url 请求路径
     * @param paramStr 参数
     * @param charset 编码格式
     * @param connectTimeout 连接超时时长
     * @param readTimeout 读取超时时长
     * @return java.lang.String
     */
    public static String postParameters(String url, String paramStr, String charset, Integer connectTimeout, Integer readTimeout) throws IOException, GeneralSecurityException {
        return post(url, paramStr, MIME_TYPE_FORM, charset, connectTimeout, readTimeout);
    }

    /**
     * post提交
     * @author zero
     * @date 2021/4/8 11:40
     * @param url 请求路径
     * @param params  请求参数
     * @return java.lang.String
     */
    public static String postParameters(String url, Map<String, String> params) throws Exception {
        return postForm(url, params, null, CONNECT_TIMEOUT, READ_TIMEOUT);
    }

    /**
     *
     * @author zero
     * @date 2021/4/8 11:41
     * @param url 请求路径
     * @param params 请求参数
     * @param connTimeout 超时时长
     * @param readTimeout 超时时长
     * @return java.lang.String
     */
    public static String postParameters(String url, Map<String, String> params, Integer connTimeout,Integer readTimeout) throws  Exception {
        return postForm(url, params, null, connTimeout, readTimeout);
    }

    /**
     * get提交，不设置超时时长
     * @author zero
     * @date 2021/4/8 11:44
     * @param url  请求路径
     * @return java.lang.String
     */
    public static String get(String url) throws Exception {
        return get(url, Consts.UTF_8.toString(), null, null);
    }

    /**
     *
     * @author zero
     * @date 2021/4/8 11:44
     * @param url 请求路径
     * @param charset 编码格式
     * @return java.lang.String
     */
    public static String get(String url, String charset) throws Exception {
        return get(url, charset, CONNECT_TIMEOUT, READ_TIMEOUT);
    }

    /**
     * 发送 post 请求
     * @author zero
     * @date 2021/4/8 10:49
     * @param url 请求Url
     * @param body 请求体
     * @param mimetype 传输类型
     * @param charset 编码格式
     * @param connectTimeout 连接超时时长
     * @param readTimeout 读取超时时长
     * @return java.lang.String
     */
    public static String post(String url, String body, String mimetype, String charset, Integer connectTimeout, Integer readTimeout) throws IOException, GeneralSecurityException {
        HttpPost post = new HttpPost(url);
        String result;
        try{
            if(StringUtils.isNotBlank(body)){
                HttpEntity entity = new StringEntity(body, ContentType.create(mimetype, charset));
                post.setEntity(entity);
            }
            // 设置参数
            RequestConfig.Builder customRequestConf = RequestConfig.custom();
            if (null != connectTimeout) {
                customRequestConf.setConnectTimeout(connectTimeout);
            }
            if (null != readTimeout) {
                customRequestConf.setSocketTimeout(readTimeout);
            }
            post.setConfig(customRequestConf.build());

            HttpResponse response;
            if (url.startsWith(PROTOCOL_HTTPS)) {
                // 执行https请求
               client = createSSLInsecureClient();
            }
            response = client.execute(post);
            result = IoUtils.toString(response.getEntity().getContent(), charset);
        } finally{
            post.releaseConnection();
            if (url.startsWith(PROTOCOL_HTTPS) && client instanceof CloseableHttpClient) {
                ((CloseableHttpClient) client).close();
            }
        }
        return  result;
    }

    /**
     * post提交form表单
     * @author zero
     * @date 2021/4/8 10:51
     * @param url 请求URl
     * @param params 请求参数
     * @param headers 请求头
     * @param connTimeout 连接超时时长
     * @param readTimeout 读取超时时长
     * @return java.lang.String
     */
    public static String postForm(String url, Map<String, String> params, Map<String, String> headers, Integer connTimeout, Integer readTimeout) throws IOException, GeneralSecurityException {
        HttpPost post = new HttpPost(url);
        try {
            if (params != null && !params.isEmpty()) {
                List<NameValuePair> formParams = new ArrayList<>();
                Set<Entry<String, String>> entrySet = params.entrySet();
                for (Entry<String, String> entry : entrySet) {
                    formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, Consts.UTF_8);
                post.setEntity(entity);
            }
            if (headers != null && !headers.isEmpty()) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    post.addHeader(entry.getKey(), entry.getValue());
                }
            }
            // 设置参数
            RequestConfig.Builder customReqConf = RequestConfig.custom();
            if (connTimeout != null) {
                customReqConf.setConnectTimeout(connTimeout);
            }
            if (readTimeout != null) {
                customReqConf.setSocketTimeout(readTimeout);
            }
            post.setConfig(customReqConf.build());
            HttpResponse res;
            if (url.startsWith(PROTOCOL_HTTPS)) {
                // 执行 Https 请求.
                client = createSSLInsecureClient();
            }
            res = client.execute(post);
            return IoUtils.toString(res.getEntity().getContent(), "UTF-8");
        } finally {
            post.releaseConnection();
            if (url.startsWith(PROTOCOL_HTTPS) && client instanceof CloseableHttpClient) {
                ((CloseableHttpClient) client).close();
            }
        }
    }

    /**
     * 发送get请求
     * @author zero
     * @date 2021/4/8 11:19
     * @param url 请求URl
     * @param charset 编码格式
     * @param connTimeout 连接超时时长
     * @param readTimeout 读取超时时长
     * @return java.lang.String
     */
    public static String get(String url, String charset, Integer connTimeout,Integer readTimeout) throws IOException, GeneralSecurityException {
        HttpGet get = new HttpGet(url);
        String result = "";
        try {
            // 设置参数
            RequestConfig.Builder customReqConf = RequestConfig.custom();
            if (connTimeout != null) {
                customReqConf.setConnectTimeout(connTimeout);
            }
            if (readTimeout != null) {
                customReqConf.setSocketTimeout(readTimeout);
            }
            get.setConfig(customReqConf.build());

            HttpResponse res = null;

            if (url.startsWith(PROTOCOL_HTTPS)) {
                // 执行 Https 请求.
                client = createSSLInsecureClient();
            }
            res = client.execute(get);

            result = IoUtils.toString(res.getEntity().getContent(), charset);
        } finally {
            get.releaseConnection();
            if (url.startsWith(PROTOCOL_HTTPS) && client instanceof CloseableHttpClient) {
                ((CloseableHttpClient) client).close();
            }
        }
        return result;
    }

    /**
     * 创建SSL 连接
     * @author zero
     * @date 2021/4/8 10:56
     * @return org.apache.http.impl.client.CloseableHttpClient
     */
    private static CloseableHttpClient createSSLInsecureClient () throws GeneralSecurityException{
        SSLContext sslContext = new SSLContextBuilder()
                .loadTrustMaterial(null, (chain, authType) -> true)
                .build();
        SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext);
        return HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build();
    }
}
